<template>
  <header class="headNav">
    <div class="left">
      <h1 ><router-link to="/index">租好房 好租房</router-link></h1>
      <ul>
        <li><router-link to="/index">首页</router-link></li>
        <li><router-link :to="{path:'/index/rentType', query:{type: '整租'}}">整租</router-link></li>
        <li><router-link :to="{path:'/index/rentType', query:{type: '合租'}}">合租</router-link></li>
        <li><router-link to="/index/news">资讯</router-link></li>
        <li><router-link to="/index/feedback">意见反馈</router-link></li>
      </ul>
    </div>
    <div v-if="!userInfo.username" class="right">
      <a href="/login">
        <i class="el-icon-user-solid"></i>
        <span style="margin-left: 5px;" >登录</span>
      </a>
      <el-button class="btnRegister" icon="el-icon-right" type="primary" @click="()=>{this.$router.push('/register')}">注册</el-button>
    </div>
    <div v-else class="right">
      <el-container>
        <el-header style="text-align: right; font-size: 20px;align-items: center;padding: 15px">
          <el-dropdown @command="handleCommand">
            <a href="#" @click.prevent>
              <img :src="defaultavatar">
               <span style="font-weight: bold">
               你好，{{userInfo.username}}（{{userInfo.role}}）<i class="el-icon-arrow-down"></i>
               </span>
            </a>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="roleDisplay !=='admin'" command="/index/admin/info"
                                icon="el-icon-user">个人中心</el-dropdown-item>

              <el-dropdown-item v-if="roleDisplay === 'renter'" command="/index/admin/adminHome"
                                icon="el-icon-house">我的房源</el-dropdown-item>

              <el-dropdown-item v-if="roleDisplay === 'renter'" command="/index/admin/collect"
                                icon="el-icon-star-off">我的收藏</el-dropdown-item>

              <el-dropdown-item v-if="roleDisplay === 'landlord'" command="/index/admin/house"
                                icon="el-icon-house" >房源管理</el-dropdown-item>

              <el-dropdown-item v-if="roleDisplay === 'landlord'" command="/index/admin/order"
                                icon="el-icon-house" >订单管理</el-dropdown-item>

              <el-dropdown-item v-if="roleDisplay === 'admin'" command="/index/admin/adminUser"
                                icon="el-icon-s-custom" >用户管理</el-dropdown-item>

              <el-dropdown-item v-if="roleDisplay === 'admin'" command="/index/admin/adminNews"
                                icon="el-icon-s-promotion" >资讯管理</el-dropdown-item>

              <el-dropdown-item v-if="roleDisplay === 'admin'" command="/index/admin/data"
                                icon="el-icon-s-data" >数据统计</el-dropdown-item>

              <el-dropdown-item command="/index" icon="el-icon-switch-button">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-header>
      </el-container>
    </div>
  </header>

</template>

<script>


export default {
  name: 'headNav',
  data() {
    return {
      user:{
        username: '',
        password: '',
        role:'Renter',
      },
      userInfo:{},
      //默认头像
      defaultavatar: require("@/assets/user-default.png"),
    };
  },
  created() {
    this.getUser()
  },
  methods: {
    getUser(){
      if (localStorage.getItem("login-user")!=null){
        let user = JSON.parse(localStorage.getItem("login-user"));
        this.userInfo = user;
        //console.log(this.userInfo)
      }
    },
    // 退出登录,并清除存储的登录信息
    /*logout() {
      this.$message.success('正在退出登录，请稍候...')
      localStorage.clear();
      setTimeout(()=>{
        this.$router.go(0);
       },999)
    },
    // 退出登录，并弹出确认框
    logout() {
      this.$confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message.success('正在退出登录，请稍候...');
        localStorage.clear();
        setTimeout(() => {
          this.$router.go(0); // 刷新页面
        }, 999);
      }).catch(() => {
        this.$message.info('已取消');
      });
    },

    handleCommand(command){
      //判断当前页面是否为首页
      if (command == '/index'){
        //不是首页就跳转//点击下拉菜单完成相关路由的跳转
        if (this.$route.path !== command){
          this.$router.push(`${command}`);
        }
         this.logout()
      }
      else{
        //目标路由与当前路由相同，则刷新页面
        if (this.$route.path == command){
          location.reload();
        }else{
          this.$router.push(`${command}`);
        }
      }
    }*/

    logout() {
      return new Promise((resolve, reject) => {
        this.$confirm('确定要退出登录吗？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$message.success('正在退出登录，请稍候...');
          localStorage.clear();
          resolve(); // 确认后继续执行后续逻辑
        }).catch(() => {
          this.$message.info('已取消');
          reject(); // 取消则中断流程
        });
      });
    },

    async handleCommand(command) {
      if (command === '/index') {
        try {
          await this.logout(); // 等待用户确认退出
          if (this.$route.path !== command) {
            await this.$router.push(command); // 确认后跳转首页
          }
        } catch (e) {
          // 用户取消退出，不跳转也不刷新
        }
      } else {
        if (this.$route.path === command) {
          location.reload();
        } else {
          await this.$router.push(command);
        }
      }
    }

  },
  computed: {
    //角色获取并显示
    roleDisplay() {
      switch (JSON.parse(localStorage.getItem("login-user")).role) {
        case '管理员':
          return 'admin';
        case '房东':
          return 'landlord';
        case '租客':
          return 'renter';
        default:
          return '';
      }
    },
  }
}
</script>

<style scoped>

.login-box>form{
  text-align: center;
}
.headNav {
  height: 70px;
  display: flex;
  background-color: white;
  justify-content: space-between;
  align-items: center;
  padding: 0 300px;

}

.left {
  display: flex;
  align-items: center;
  list-style: none;
}
.left h1{
  font-size: 25px;
  font-weight: 600;
  color: #666565;
}
.left ul {
  display: flex;
  align-items: center;
  margin-left: 50px;
  font-weight: 600;
}

.left ul li {
  margin-left: 30px;
  list-style: none;
}

a {
  text-decoration: none;
  color: inherit;
}

.left img {
  width: 150px;
  height: 50px;
}

.btnRegister {
  color: white;
  background-color: #160b41;
  border: none;
  margin-left: 20px;
}

.right {
  display: flex;
  align-items: center;
}

.right a {
  color: #4696ef;
}

/* else的css */
.right img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 5px;
}

.right a {
  display: flex;
  align-items: center;
  color: #777;
  font-weight: 600;
}
</style>